3 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
26 class ApiUpload
extends ApiBase
{
27 /** @var UploadBase|UploadFromChunks */
28 protected $mUpload = null;
32 public function execute() {
33 // Check whether upload is enabled
34 if ( !UploadBase
::isEnabled() ) {
35 $this->dieWithError( 'uploaddisabled' );
38 $user = $this->getUser();
41 $this->mParams
= $this->extractRequestParams();
42 $request = $this->getMain()->getRequest();
43 // Check if async mode is actually supported (jobs done in cli mode)
44 $this->mParams
['async'] = ( $this->mParams
['async'] &&
45 $this->getConfig()->get( 'EnableAsyncUploads' ) );
46 // Add the uploaded file to the params array
47 $this->mParams
['file'] = $request->getFileName( 'file' );
48 $this->mParams
['chunk'] = $request->getFileName( 'chunk' );
50 // Copy the session key to the file key, for backward compatibility.
51 if ( !$this->mParams
['filekey'] && $this->mParams
['sessionkey'] ) {
52 $this->mParams
['filekey'] = $this->mParams
['sessionkey'];
55 // Select an upload module
57 if ( !$this->selectUploadModule() ) {
58 return; // not a true upload, but a status request or similar
59 } elseif ( !isset( $this->mUpload
) ) {
60 $this->dieDebug( __METHOD__
, 'No upload module set' );
62 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
63 $this->dieStatus( $this->handleStashException( $e ) );
66 // First check permission to upload
67 $this->checkPermissions( $user );
69 // Fetch the file (usually a no-op)
70 /** @var Status $status */
71 $status = $this->mUpload
->fetchFile();
72 if ( !$status->isGood() ) {
73 $this->dieStatus( $status );
76 // Check if the uploaded file is sane
77 if ( $this->mParams
['chunk'] ) {
78 $maxSize = UploadBase
::getMaxUploadSize();
79 if ( $this->mParams
['filesize'] > $maxSize ) {
80 $this->dieWithError( 'file-too-large' );
82 if ( !$this->mUpload
->getTitle() ) {
83 $this->dieWithError( 'illegal-filename' );
85 } elseif ( $this->mParams
['async'] && $this->mParams
['filekey'] ) {
86 // defer verification to background process
88 wfDebug( __METHOD__
. " about to verify\n" );
89 $this->verifyUpload();
92 // Check if the user has the rights to modify or overwrite the requested title
93 // (This check is irrelevant if stashing is already requested, since the errors
94 // can always be fixed by changing the title)
95 if ( !$this->mParams
['stash'] ) {
96 $permErrors = $this->mUpload
->verifyTitlePermissions( $user );
97 if ( $permErrors !== true ) {
98 $this->dieRecoverableError( $permErrors, 'filename' );
102 // Get the result based on the current upload context:
104 $result = $this->getContextResult();
105 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
106 $this->dieStatus( $this->handleStashException( $e ) );
108 $this->getResult()->addValue( null, $this->getModuleName(), $result );
110 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
111 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
112 if ( $result['result'] === 'Success' ) {
113 $imageinfo = $this->mUpload
->getImageInfo( $this->getResult() );
114 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
117 // Cleanup any temporary mess
118 $this->mUpload
->cleanupTempFile();
122 * Get an upload result based on upload context
125 private function getContextResult() {
126 $warnings = $this->getApiWarnings();
127 if ( $warnings && !$this->mParams
['ignorewarnings'] ) {
128 // Get warnings formatted in result array format
129 return $this->getWarningsResult( $warnings );
130 } elseif ( $this->mParams
['chunk'] ) {
131 // Add chunk, and get result
132 return $this->getChunkResult( $warnings );
133 } elseif ( $this->mParams
['stash'] ) {
134 // Stash the file and get stash result
135 return $this->getStashResult( $warnings );
138 // Check throttle after we've handled warnings
139 if ( UploadBase
::isThrottled( $this->getUser() )
141 $this->dieWithError( 'apierror-ratelimited' );
144 // This is the most common case -- a normal upload with no warnings
145 // performUpload will return a formatted properly for the API with status
146 return $this->performUpload( $warnings );
150 * Get Stash Result, throws an exception if the file could not be stashed.
151 * @param array $warnings Array of Api upload warnings
154 private function getStashResult( $warnings ) {
156 $result['result'] = 'Success';
157 if ( $warnings && count( $warnings ) > 0 ) {
158 $result['warnings'] = $warnings;
160 // Some uploads can request they be stashed, so as not to publish them immediately.
161 // In this case, a failure to stash ought to be fatal
162 $this->performStash( 'critical', $result );
168 * Get Warnings Result
169 * @param array $warnings Array of Api upload warnings
172 private function getWarningsResult( $warnings ) {
174 $result['result'] = 'Warning';
175 $result['warnings'] = $warnings;
176 // in case the warnings can be fixed with some further user action, let's stash this upload
177 // and return a key they can use to restart it
178 $this->performStash( 'optional', $result );
184 * Get the result of a chunk upload.
185 * @param array $warnings Array of Api upload warnings
188 private function getChunkResult( $warnings ) {
191 if ( $warnings && count( $warnings ) > 0 ) {
192 $result['warnings'] = $warnings;
195 $request = $this->getMain()->getRequest();
196 $chunkPath = $request->getFileTempname( 'chunk' );
197 $chunkSize = $request->getUpload( 'chunk' )->getSize();
198 $totalSoFar = $this->mParams
['offset'] +
$chunkSize;
199 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
201 // Sanity check sizing
202 if ( $totalSoFar > $this->mParams
['filesize'] ) {
203 $this->dieWithError( 'apierror-invalid-chunk' );
206 // Enforce minimum chunk size
207 if ( $totalSoFar != $this->mParams
['filesize'] && $chunkSize < $minChunkSize ) {
208 $this->dieWithError( [ 'apierror-chunk-too-small', Message
::numParam( $minChunkSize ) ] );
211 if ( $this->mParams
['offset'] == 0 ) {
212 $filekey = $this->performStash( 'critical' );
214 $filekey = $this->mParams
['filekey'];
216 // Don't allow further uploads to an already-completed session
217 $progress = UploadBase
::getSessionStatus( $this->getUser(), $filekey );
219 // Probably can't get here, but check anyway just in case
220 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
221 } elseif ( $progress['result'] !== 'Continue' ||
$progress['stage'] !== 'uploading' ) {
222 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
225 $status = $this->mUpload
->addChunk(
226 $chunkPath, $chunkSize, $this->mParams
['offset'] );
227 if ( !$status->isGood() ) {
229 'offset' => $this->mUpload
->getOffset(),
232 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
236 // Check we added the last chunk:
237 if ( $totalSoFar == $this->mParams
['filesize'] ) {
238 if ( $this->mParams
['async'] ) {
239 UploadBase
::setSessionStatus(
242 [ 'result' => 'Poll',
243 'stage' => 'queued', 'status' => Status
::newGood() ]
245 JobQueueGroup
::singleton()->push( new AssembleUploadChunksJob(
246 Title
::makeTitle( NS_FILE
, $filekey ),
248 'filename' => $this->mParams
['filename'],
249 'filekey' => $filekey,
250 'session' => $this->getContext()->exportSession()
253 $result['result'] = 'Poll';
254 $result['stage'] = 'queued';
256 $status = $this->mUpload
->concatenateChunks();
257 if ( !$status->isGood() ) {
258 UploadBase
::setSessionStatus(
261 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
263 $this->dieStatusWithCode( $status, 'stashfailed' );
266 // We can only get warnings like 'duplicate' after concatenating the chunks
267 $warnings = $this->getApiWarnings();
269 $result['warnings'] = $warnings;
272 // The fully concatenated file has a new filekey. So remove
273 // the old filekey and fetch the new one.
274 UploadBase
::setSessionStatus( $this->getUser(), $filekey, false );
275 $this->mUpload
->stash
->removeFile( $filekey );
276 $filekey = $this->mUpload
->getStashFile()->getFileKey();
278 $result['result'] = 'Success';
281 UploadBase
::setSessionStatus(
285 'result' => 'Continue',
286 'stage' => 'uploading',
287 'offset' => $totalSoFar,
288 'status' => Status
::newGood(),
291 $result['result'] = 'Continue';
292 $result['offset'] = $totalSoFar;
295 $result['filekey'] = $filekey;
301 * Stash the file and add the file key, or error information if it fails, to the data.
303 * @param string $failureMode What to do on failure to stash:
304 * - When 'critical', use dieStatus() to produce an error response and throw an exception.
305 * Use this when stashing the file was the primary purpose of the API request.
306 * - When 'optional', only add a 'stashfailed' key to the data and return null.
307 * Use this when some error happened for a non-stash upload and we're stashing the file
308 * only to save the client the trouble of re-uploading it.
309 * @param array &$data API result to which to add the information
310 * @return string|null File key
312 private function performStash( $failureMode, &$data = null ) {
313 $isPartial = (bool)$this->mParams
['chunk'];
315 $status = $this->mUpload
->tryStashFile( $this->getUser(), $isPartial );
317 if ( $status->isGood() && !$status->getValue() ) {
318 // Not actually a 'good' status...
319 $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
321 } catch ( Exception
$e ) {
322 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
323 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
324 $status = Status
::newFatal( $this->getErrorFormatter()->getMessageFromException(
325 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
329 if ( $status->isGood() ) {
330 $stashFile = $status->getValue();
331 $data['filekey'] = $stashFile->getFileKey();
332 // Backwards compatibility
333 $data['sessionkey'] = $data['filekey'];
334 return $data['filekey'];
337 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
338 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
339 // Statuses for it. Just extract the exception details and parse them ourselves.
340 list( $exceptionType, $message ) = $status->getMessage()->getParams();
341 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
342 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
346 if ( $failureMode !== 'optional' ) {
347 $this->dieStatus( $status );
349 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
355 * Throw an error that the user can recover from by providing a better
356 * value for $parameter
358 * @param array $errors Array of Message objects, message keys, key+param
359 * arrays, or StatusValue::getErrors()-style arrays
360 * @param string|null $parameter Parameter that needs revising
361 * @throws ApiUsageException
363 private function dieRecoverableError( $errors, $parameter = null ) {
364 $this->performStash( 'optional', $data );
367 $data['invalidparameter'] = $parameter;
370 $sv = StatusValue
::newGood();
371 foreach ( $errors as $error ) {
372 $msg = ApiMessage
::create( $error );
373 $msg->setApiData( $msg->getApiData() +
$data );
376 $this->dieStatus( $sv );
380 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
383 * @param Status $status
384 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
385 * @param array|null $moreExtraData
386 * @throws ApiUsageException
388 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
389 $sv = StatusValue
::newGood();
390 foreach ( $status->getErrors() as $error ) {
391 $msg = ApiMessage
::create( $error, $overrideCode );
392 if ( $moreExtraData ) {
393 $msg->setApiData( $msg->getApiData() +
$moreExtraData );
397 $this->dieStatus( $sv );
401 * Select an upload module and set it to mUpload. Dies on failure. If the
402 * request was a status request and not a true upload, returns false;
407 protected function selectUploadModule() {
408 $request = $this->getMain()->getRequest();
410 // chunk or one and only one of the following parameters is needed
411 if ( !$this->mParams
['chunk'] ) {
412 $this->requireOnlyOneParameter( $this->mParams
,
413 'filekey', 'file', 'url' );
416 // Status report for "upload to stash"/"upload from stash"
417 if ( $this->mParams
['filekey'] && $this->mParams
['checkstatus'] ) {
418 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
420 $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
421 } elseif ( !$progress['status']->isGood() ) {
422 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
424 if ( isset( $progress['status']->value
['verification'] ) ) {
425 $this->checkVerification( $progress['status']->value
['verification'] );
427 if ( isset( $progress['status']->value
['warnings'] ) ) {
428 $warnings = $this->transformWarnings( $progress['status']->value
['warnings'] );
430 $progress['warnings'] = $warnings;
433 unset( $progress['status'] ); // remove Status object
435 if ( isset( $progress['imageinfo'] ) ) {
436 $imageinfo = $progress['imageinfo'];
437 unset( $progress['imageinfo'] );
440 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
441 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
442 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
444 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
450 // The following modules all require the filename parameter to be set
451 if ( is_null( $this->mParams
['filename'] ) ) {
452 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
455 if ( $this->mParams
['chunk'] ) {
457 $this->mUpload
= new UploadFromChunks( $this->getUser() );
458 if ( isset( $this->mParams
['filekey'] ) ) {
459 if ( $this->mParams
['offset'] === 0 ) {
460 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
464 $this->mUpload
->continueChunks(
465 $this->mParams
['filename'],
466 $this->mParams
['filekey'],
467 $request->getUpload( 'chunk' )
470 if ( $this->mParams
['offset'] !== 0 ) {
471 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
474 // handle first chunk
475 $this->mUpload
->initialize(
476 $this->mParams
['filename'],
477 $request->getUpload( 'chunk' )
480 } elseif ( isset( $this->mParams
['filekey'] ) ) {
481 // Upload stashed in a previous request
482 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
483 $this->dieWithError( 'apierror-invalid-file-key' );
486 $this->mUpload
= new UploadFromStash( $this->getUser() );
487 // This will not download the temp file in initialize() in async mode.
488 // We still have enough information to call checkWarnings() and such.
489 $this->mUpload
->initialize(
490 $this->mParams
['filekey'], $this->mParams
['filename'], !$this->mParams
['async']
492 } elseif ( isset( $this->mParams
['file'] ) ) {
493 // Can't async upload directly from a POSTed file, we'd have to
494 // stash the file and then queue the publish job. The user should
495 // just submit the two API queries to perform those two steps.
496 if ( $this->mParams
['async'] ) {
497 $this->dieWithError( 'apierror-cannot-async-upload-file' );
500 $this->mUpload
= new UploadFromFile();
501 $this->mUpload
->initialize(
502 $this->mParams
['filename'],
503 $request->getUpload( 'file' )
505 } elseif ( isset( $this->mParams
['url'] ) ) {
506 // Make sure upload by URL is enabled:
507 if ( !UploadFromUrl
::isEnabled() ) {
508 $this->dieWithError( 'copyuploaddisabled' );
511 if ( !UploadFromUrl
::isAllowedHost( $this->mParams
['url'] ) ) {
512 $this->dieWithError( 'apierror-copyuploadbaddomain' );
515 if ( !UploadFromUrl
::isAllowedUrl( $this->mParams
['url'] ) ) {
516 $this->dieWithError( 'apierror-copyuploadbadurl' );
519 $this->mUpload
= new UploadFromUrl
;
520 $this->mUpload
->initialize( $this->mParams
['filename'],
521 $this->mParams
['url'] );
528 * Checks that the user has permissions to perform this upload.
529 * Dies with usage message on inadequate permissions.
530 * @param User $user The user to check.
532 protected function checkPermissions( $user ) {
533 // Check whether the user has the appropriate permissions to upload anyway
534 $permission = $this->mUpload
->isAllowed( $user );
536 if ( $permission !== true ) {
537 if ( !$user->isLoggedIn() ) {
538 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
541 $this->dieStatus( User
::newFatalPermissionDeniedStatus( $permission ) );
545 if ( $user->isBlockedFromUpload() ) {
546 $this->dieBlocked( $user->getBlock() );
550 if ( $user->isBlockedGlobally() ) {
551 $this->dieBlocked( $user->getGlobalBlock() );
556 * Performs file verification, dies on error.
558 protected function verifyUpload() {
559 $verification = $this->mUpload
->verifyUpload();
560 if ( $verification['status'] === UploadBase
::OK
) {
564 $this->checkVerification( $verification );
568 * Performs file verification, dies on error.
569 * @param array $verification
571 protected function checkVerification( array $verification ) {
572 switch ( $verification['status'] ) {
573 // Recoverable errors
574 case UploadBase
::MIN_LENGTH_PARTNAME
:
575 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
577 case UploadBase
::ILLEGAL_FILENAME
:
578 $this->dieRecoverableError(
579 [ ApiMessage
::create(
580 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
584 case UploadBase
::FILENAME_TOO_LONG
:
585 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
587 case UploadBase
::FILETYPE_MISSING
:
588 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
590 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
591 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
594 // Unrecoverable errors
595 case UploadBase
::EMPTY_FILE
:
596 $this->dieWithError( 'empty-file' );
598 case UploadBase
::FILE_TOO_LARGE
:
599 $this->dieWithError( 'file-too-large' );
602 case UploadBase
::FILETYPE_BADTYPE
:
604 'filetype' => $verification['finalExt'],
605 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
607 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
609 'filetype-banned-type',
610 null, // filled in below
611 Message
::listParam( $extensions, 'comma' ),
612 count( $extensions ),
613 null, // filled in below
615 ApiResult
::setIndexedTagName( $extradata['allowed'], 'ext' );
617 if ( isset( $verification['blacklistedExt'] ) ) {
618 $msg[1] = Message
::listParam( $verification['blacklistedExt'], 'comma' );
619 $msg[4] = count( $verification['blacklistedExt'] );
620 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
621 ApiResult
::setIndexedTagName( $extradata['blacklisted'], 'ext' );
623 $msg[1] = $verification['finalExt'];
627 $this->dieWithError( $msg, 'filetype-banned', $extradata );
630 case UploadBase
::VERIFICATION_ERROR
:
631 $msg = ApiMessage
::create( $verification['details'], 'verification-error' );
632 if ( $verification['details'][0] instanceof MessageSpecifier
) {
633 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
635 $details = $verification['details'];
637 ApiResult
::setIndexedTagName( $details, 'detail' );
638 $msg->setApiData( $msg->getApiData() +
[ 'details' => $details ] );
639 $this->dieWithError( $msg );
642 case UploadBase
::HOOK_ABORTED
:
643 $msg = $verification['error'] === '' ?
'hookaborted' : $verification['error'];
644 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
647 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
648 [ 'details' => [ 'code' => $verification['status'] ] ] );
655 * Returns a suitable array for inclusion into API results if there were warnings
656 * Returns the empty array if there were no warnings
660 protected function getApiWarnings() {
661 $warnings = $this->mUpload
->checkWarnings();
663 return $this->transformWarnings( $warnings );
666 protected function transformWarnings( $warnings ) {
669 ApiResult
::setIndexedTagName( $warnings, 'warning' );
671 if ( isset( $warnings['duplicate'] ) ) {
673 /** @var File $dupe */
674 foreach ( $warnings['duplicate'] as $dupe ) {
675 $dupes[] = $dupe->getName();
677 ApiResult
::setIndexedTagName( $dupes, 'duplicate' );
678 $warnings['duplicate'] = $dupes;
681 if ( isset( $warnings['exists'] ) ) {
682 $warning = $warnings['exists'];
683 unset( $warnings['exists'] );
684 /** @var LocalFile $localFile */
685 $localFile = $warning['normalizedFile'] ??
$warning['file'];
686 $warnings[$warning['warning']] = $localFile->getName();
689 if ( isset( $warnings['no-change'] ) ) {
690 /** @var File $file */
691 $file = $warnings['no-change'];
692 unset( $warnings['no-change'] );
694 $warnings['nochange'] = [
695 'timestamp' => wfTimestamp( TS_ISO_8601
, $file->getTimestamp() )
699 if ( isset( $warnings['duplicate-version'] ) ) {
701 /** @var File $dupe */
702 foreach ( $warnings['duplicate-version'] as $dupe ) {
704 'timestamp' => wfTimestamp( TS_ISO_8601
, $dupe->getTimestamp() )
707 unset( $warnings['duplicate-version'] );
709 ApiResult
::setIndexedTagName( $dupes, 'ver' );
710 $warnings['duplicateversions'] = $dupes;
718 * Handles a stash exception, giving a useful error to the user.
719 * @todo Internationalize the exceptions then get rid of this
720 * @param Exception $e
721 * @return StatusValue
723 protected function handleStashException( $e ) {
724 switch ( get_class( $e ) ) {
725 case UploadStashFileNotFoundException
::class:
726 $wrap = 'apierror-stashedfilenotfound';
728 case UploadStashBadPathException
::class:
729 $wrap = 'apierror-stashpathinvalid';
731 case UploadStashFileException
::class:
732 $wrap = 'apierror-stashfilestorage';
734 case UploadStashZeroLengthFileException
::class:
735 $wrap = 'apierror-stashzerolength';
737 case UploadStashNotLoggedInException
::class:
738 return StatusValue
::newFatal( ApiMessage
::create(
739 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
741 case UploadStashWrongOwnerException
::class:
742 $wrap = 'apierror-stashwrongowner';
744 case UploadStashNoSuchKeyException
::class:
745 $wrap = 'apierror-stashnosuchfilekey';
748 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
751 return StatusValue
::newFatal(
752 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
757 * Perform the actual upload. Returns a suitable result array on success;
760 * @param array $warnings Array of Api upload warnings
763 protected function performUpload( $warnings ) {
764 // Use comment as initial page text by default
765 if ( is_null( $this->mParams
['text'] ) ) {
766 $this->mParams
['text'] = $this->mParams
['comment'];
769 /** @var LocalFile $file */
770 $file = $this->mUpload
->getLocalFile();
772 // For preferences mode, we want to watch if 'watchdefault' is set,
773 // or if the *file* doesn't exist, and either 'watchuploads' or
774 // 'watchcreations' is set. But getWatchlistValue()'s automatic
775 // handling checks if the *title* exists or not, so we need to check
776 // all three preferences manually.
777 $watch = $this->getWatchlistValue(
778 $this->mParams
['watchlist'], $file->getTitle(), 'watchdefault'
781 if ( !$watch && $this->mParams
['watchlist'] == 'preferences' && !$file->exists() ) {
783 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
784 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
788 // Deprecated parameters
789 if ( $this->mParams
['watch'] ) {
793 if ( $this->mParams
['tags'] ) {
794 $status = ChangeTags
::canAddTagsAccompanyingChange( $this->mParams
['tags'], $this->getUser() );
795 if ( !$status->isOK() ) {
796 $this->dieStatus( $status );
800 // No errors, no warnings: do the upload
801 if ( $this->mParams
['async'] ) {
802 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
803 if ( $progress && $progress['result'] === 'Poll' ) {
804 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
806 UploadBase
::setSessionStatus(
808 $this->mParams
['filekey'],
809 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status
::newGood() ]
811 JobQueueGroup
::singleton()->push( new PublishStashedFileJob(
812 Title
::makeTitle( NS_FILE
, $this->mParams
['filename'] ),
814 'filename' => $this->mParams
['filename'],
815 'filekey' => $this->mParams
['filekey'],
816 'comment' => $this->mParams
['comment'],
817 'tags' => $this->mParams
['tags'],
818 'text' => $this->mParams
['text'],
820 'session' => $this->getContext()->exportSession()
823 $result['result'] = 'Poll';
824 $result['stage'] = 'queued';
826 /** @var Status $status */
827 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
828 $this->mParams
['text'], $watch, $this->getUser(), $this->mParams
['tags'] );
830 if ( !$status->isGood() ) {
831 $this->dieRecoverableError( $status->getErrors() );
833 $result['result'] = 'Success';
836 $result['filename'] = $file->getName();
837 if ( $warnings && count( $warnings ) > 0 ) {
838 $result['warnings'] = $warnings;
844 public function mustBePosted() {
848 public function isWriteMode() {
852 public function getAllowedParams() {
855 ApiBase
::PARAM_TYPE
=> 'string',
858 ApiBase
::PARAM_DFLT
=> ''
861 ApiBase
::PARAM_TYPE
=> 'tags',
862 ApiBase
::PARAM_ISMULTI
=> true,
865 ApiBase
::PARAM_TYPE
=> 'text',
868 ApiBase
::PARAM_DFLT
=> false,
869 ApiBase
::PARAM_DEPRECATED
=> true,
872 ApiBase
::PARAM_DFLT
=> 'preferences',
873 ApiBase
::PARAM_TYPE
=> [
879 'ignorewarnings' => false,
881 ApiBase
::PARAM_TYPE
=> 'upload',
886 ApiBase
::PARAM_DEPRECATED
=> true,
891 ApiBase
::PARAM_TYPE
=> 'integer',
892 ApiBase
::PARAM_MIN
=> 0,
893 ApiBase
::PARAM_MAX
=> UploadBase
::getMaxUploadSize(),
896 ApiBase
::PARAM_TYPE
=> 'integer',
897 ApiBase
::PARAM_MIN
=> 0,
900 ApiBase
::PARAM_TYPE
=> 'upload',
904 'checkstatus' => false,
910 public function needsToken() {
914 protected function getExamplesMessages() {
916 'action=upload&filename=Wiki.png' .
917 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
918 => 'apihelp-upload-example-url',
919 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
920 => 'apihelp-upload-example-filekey',
924 public function getHelpUrls() {
925 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';